﻿using NHibernate;
using NHibernate.Cfg;
using System;
using System.Collections.Generic;

namespace Data.NHibernate
{
    public class Helper
    {
        private static readonly object lockObj = new object();
        //SessionFactory组
        private static Dictionary<string, ISessionFactory> sessionFactoryList = new Dictionary<string, ISessionFactory>();

        public Helper()
        {
        }

        /// <summary>
        /// 数据库名称
        /// </summary>
        private static string DataBase
        {
            get;
            set;
        }

        /// <summary>
        /// 获取SessionFactory
        /// </summary>
        private static ISessionFactory iSessionFactory
        {
            get
            {
                //多线程锁定双重判断
                if (!sessionFactoryList.ContainsKey(DataBase))
                {
                    lock (lockObj)
                    {
                        if (!sessionFactoryList.ContainsKey(DataBase))
                        {
                            //获取对应的SessionFactory，并放入到SessionFactory集合中
                            ISessionFactory _iSessionFactory = (new Configuration()).Configure(string.Format("{0}{1}.cfg.config", AppDomain.CurrentDomain.BaseDirectory, DataBase)).BuildSessionFactory();
                            sessionFactoryList.Add(DataBase, _iSessionFactory);
                        }
                    }
                }
                return sessionFactoryList[DataBase];
            }
        }

        /// <summary>
        /// 获取Session对象
        /// </summary>
        /// <returns></returns>
        public static ISession GetSession()
        {
            return iSessionFactory.OpenSession();
        }

        /// <summary>
        /// 获取Session对象
        /// </summary>
        /// <returns></returns>
        public static ISession GetSession(string dataBase)
        {
            if (string.IsNullOrEmpty(dataBase))
                dataBase = "hibernate";
            DataBase = dataBase;
            return iSessionFactory.OpenSession();
        }
    }
}
